package ithink.link.dao;

import java.io.IOException;

import ithink.link.ConfigHelper;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zaqb on 17-11-21.
 */

public class ItkMemcached {
    private static final Logger LOGGER = LoggerFactory.getLogger(ItkMemcached.class);

    private String host = "m-m5e0cfce11af6a44.memcache.rds.aliyuncs.com";//控制台上的“内网地址”
    private String port ="11211"; //默认端口 11211，不用改
    private String username = "OCS_DEV";//控制台上的“实例ID”，新版ocs的username可以置空
    private String password = "g593tAys05ts8ttn";//邮件中提供的“密码”
    private MemcachedClient cache = null;
    private AuthDescriptor ad = null;
    private final Object jobj = new Object();

    public ItkMemcached(String host, String port, String username, String password) throws IOException {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;

        ad = new AuthDescriptor(new String[]{"PLAIN"}, new PlainCallbackHandler(username, password));
        cache = new MemcachedClient(
                new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
                        .setAuthDescriptor(ad)
                        .build(),
                AddrUtil.getAddresses(host + ":" + port));
    }


    public void set(String key, String value, Integer expireTime) {
        synchronized (jobj) {
            try {
                if(cache == null) {
                    LOGGER.error( "cache is null" );
                    return;
                }
                LOGGER.info( "set key:{} value:{},ttl:{}"
                        , key
                ,value, expireTime);

                cache.set(  key, expireTime, value );
            }catch (Exception ex) {
                LOGGER.error("error set key" + key, ex);
            }
        }
    }



    public void del(String key) {
        synchronized (jobj) {
            try {
                if(cache == null) {
                    return;
                }
                cache.delete(  key );
            } catch (Exception ex) {
                LOGGER.error("error delete key" + key, ex);
            }
        }
    }


    public static void main(String[] args) throws IOException {
        final String host = "m-m5e0cfce11af6a44.memcache.rds.aliyuncs.com";//控制台上的“内网地址”
        final String port ="11211"; //默认端口 11211，不用改
        final String username = "OCS_DEV";//控制台上的“实例ID”，新版ocs的username可以置空
        final String password = "g593tAys05ts8ttn";//邮件中提供的“密码”

        ItkMemcached memcached = new ItkMemcached(host, port, username, password);
    }
}
